﻿using System.Text.Json;
using Ding.HttpHelper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SelfService.HaiTai.Models;
using SelfService.Model;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using SelfService.Model.ViewModels;
using TT;
using WalkingTec.Mvvm.Core;
using Web.Models.His;

namespace SelfService.HaiTai
{
    public class HaiTaiUser : IHisUser
    {
        private readonly WTMContext _wtm;
        private readonly string _url;

        public HaiTaiUser(IOptions<AppSettings> options, WTMContext wtm)
        {
            _wtm = wtm;
            this._url = options.Value.HisUrl;
        }

        public Task<ResultDetail<IPatient>> GetUser(IPatient patient, SysClient client, SysOperator @operator)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public async Task<ResultDetail<IPatient>> GetUser(SysPatientSearcher search)
        {
            HttpResult result = default;
            var postData = new GetUserValidate();
            postData.CardNo = search.IdCardNo;
            postData.UserId = _wtm.LoginUserInfo.ITCode;
            var httpItem = new HttpItem()
            {
                URL = $"{this._url}/GetValue",
                Method = "POST",
                ContentType = "application/json",
                Postdata = JsonSerializer.Serialize(postData)
            };
            try
            {
                await Task.Run(() =>
                {
                    result = new HttpHelper().GetHtml(httpItem);
                });
                
                if (TryJsonParse(result.Html, out HisResult<List<GetUserResponse>> response))
                {
                    if (response.ResultCode == "0")
                    {
                        var element = response.Data.FirstOrDefault();
                        if (element != null)
                        {
                            var patient = new SysPatient
                            {
                                CardNo = element.CardNo,
                                IdCardNo = element.IDCardNo,
                                Balance = element.AvailableAmt ?? 0,
                                Name = element.PatName,
                                Phone = element.tel,
                                HisCode = element.patId,
                                CreateTime = element.bindingDate
                            };
                            if (Common.CheckIdCardNo(patient.IdCardNo))
                            {
                                patient.Sex = Common.GetSexByIdCardNo(search.IdCardNo) == 0 ? SexEnum.女 : SexEnum.男;
                                patient.Age = Common.GetAgeByIdCardNo(search.IdCardNo);
                            }
                            return new ResultDetail<IPatient>
                            {
                                Data = patient,
                                Request = httpItem.Postdata,
                                Response = result.Html
                            };
                        }
                        return new ResultDetail<IPatient>
                        {
                            Code = 1,
                            Message = "用户信息为空",
                            Request = httpItem.Postdata,
                            Response = result.Html
                        };
                    }
                    else
                    {
                        if (response.ErrorMsg.Contains("该卡号未建档"))
                        {
                            //未建档
                            return new ResultDetail<IPatient>()
                            {
                                Code = 2,
                                Message = response.ErrorMsg,
                                Request = httpItem.Postdata,
                                Response = result.Html
                            };
                        }
                        //其他错误
                        return new ResultDetail<IPatient>()
                        {
                            Code = 1,
                            Message = response.ErrorMsg,
                            Request = httpItem.Postdata,
                            Response = result.Html
                        };
                    }
                }
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = "查询失败, 返回数据解析异常.",
                    Request = httpItem.Postdata,
                    Response = result.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = $"查询异常:{e.Message}",
                    Request = httpItem.Postdata
                };
            }
        }


        public Task<ResultDetail<IPatient>> GetUser(BaseSearcher search)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 建档
        /// </summary>
        /// <param name="patient"></param>
        /// <param name="client"></param>
        /// <param name="operator"></param>
        /// <returns></returns>
        public async Task<ResultDetail<IPatient>> Reg(IPatient patient)
        {
            var user = await _wtm.DC.Set<FrameworkUser>()
                .FirstOrDefaultAsync(e => e.ID == Guid.Parse(_wtm.LoginUserInfo.UserId));
            if (user == null)
            {
                throw new ArgumentException("没有找到操作员信息.");
            }
            HttpResult result = default;
            var postData = new AddUserValidate();
            postData.PatientName = patient.Name;
            postData.IDCardNo = patient.IdCardNo;
            postData.Tel = patient.Phone;
            postData.Uid = patient.Uid;
            postData.Address = patient.Address;
            postData.UserId = user.ITCode;
            postData.MacAddress = user.ITCode;
            var httpItem = new HttpItem()
            {
                URL = $"{_url}/GetValue",
                Method = "POST",
                ContentType = "application/json",
                Postdata = JsonSerializer.Serialize(postData)
            };
            try
            {
                await Task.Run(() =>
                {
                    result = new HttpHelper().GetHtml(httpItem);
                });
                if (result.Html.TryJsonParse(out HisResult<HisRegUserResponse[]> response))
                {
                    if (response.ResultCode == "0" && response.Data?.Length > 0)
                    {
                        patient.HisCode = response.Data[0].PatientId;
                        patient.CardNo = response.Data[0].HealthCardNo;
                        return new ResultDetail<IPatient>()
                        {
                            Data = patient,
                            Message = response.ErrorMsg,
                            Request = httpItem.Postdata,
                            Response = result.Html
                        };
                    }
                    else
                    {
                        if (response.Data?.Length > 0 && !response.Data[0].PatientId.IsNullOrWhiteSpace())
                        {
                            return new ResultDetail<IPatient>()
                            {
                                Code = 1,
                                Message = "用户已经建档, 请勿重复建档.",
                                Request = httpItem.Postdata,
                                Response = result.Html
                            };
                        }
                        //其他错误
                        return new ResultDetail<IPatient>()
                        {
                            Code = 1,
                            Message = response.ErrorMsg,
                            Request = httpItem.Postdata,
                            Response = result.Html
                        };
                    }
                }
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = "建档失败, 返回数据解析异常.",
                    Request = httpItem.Postdata,
                    Response = result.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = $"建档异常:{JsonSerializer.Serialize(e)}",
                    Request = httpItem.Postdata
                };
            }
        }

        public Task<ResultDetail<IPatient>> GetUserByECode(string code, SysClient client, SysOperator @operator)
        {
            throw new NotImplementedException();
        }
        
        private bool TryJsonParse<T>(string json, out T data)
        {
            data = default;
            try
            {
                data = JsonSerializer.Deserialize<T>(json);
                return data != null;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }

    public class HisRegUserResponse
    {
        public string PatientId { get; set; }
        
        public string HealthCardNo { get; set; }
    }
}